#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#define DEBUG
#ifdef DEBUG
#define dbgprint(format,args...) ({ \
		fprintf (stderr, "[%s] <%d>-->", __func__, __LINE__); \
		fprintf(stderr, format, ##args);})
#else
#define dbgprint(format,args...)
#endif


static const char *usbpath = "/dev/sdc1";
#define OFFSET_FLAG 1024

int main()
{
	int ret;
	char *flag = "hello world";
	char *readbuf = NULL;
	FILE *fp;
	unsigned int len = 0;

	fp = fopen(usbpath, "wb+");
	if (!fp) {
		dbgprint("fopen error %s\n", strerror(errno));
		goto fail1;
	}

	len = strlen(flag);
	fseek(fp, OFFSET_FLAG, SEEK_SET);

	ret = fwrite(flag, 1, len, fp);
	if (ret != len) {
		dbgprint("fwrite failed\n");
		goto fail2;
	}
	fsync(fileno(fp));

	readbuf = (char *)calloc(len, 1);
	fseek(fp, 0L, SEEK_SET);
	fseek(fp, OFFSET_FLAG, SEEK_SET);
	ret = fread(readbuf, len, 1, fp);
	dbgprint("%d:%s\n", len, readbuf);
	if (ret < 0) {
		dbgprint("fread failed, ret=%d\n", ret);
		goto fail2;
	}

	if (fclose(fp) < 0) {
		dbgprint("fclose failed\n");
		goto fail2;
	}

	return 0;
fail2:
	fclose(fp);
fail1:
	return -1;
}
